<template>
  <el-drawer
    :model-value="!!editorStore.drawerNodeId" 
    :title="drawerTitle"
    @closed="handleClose" 
    direction="rtl"
    size="450px"
    class="node-details-drawer"
  >
    <div v-if="nodeData" class="drawer-content">
      <!-- Basic Info -->
      <el-descriptions :column="1" border class="node-info-section">
        <el-descriptions-item label="节点名称">{{ nodeData.data.nodeName }}</el-descriptions-item>
        <el-descriptions-item label="节点 ID">{{ nodeData.id }}</el-descriptions-item>
        <el-descriptions-item label="类型">{{ nodeData.type }}</el-descriptions-item>
        <el-descriptions-item label="层级">{{ nodeData.data.level }}</el-descriptions-item>
        <el-descriptions-item label="父节点 ID">{{ nodeData.parentId || '无' }}</el-descriptions-item>
      </el-descriptions>

      <!-- Attributes -->
      <el-divider>属性</el-divider>
      <div class="attributes-section">
        <el-table :data="nodeData.data.attributes" style="width: 100%" size="small" stripe border empty-text="无属性">
          <el-table-column prop="name" label="名称" width="150">
             <template #default="{ row }">
                 <el-input v-if="row.isEditing" v-model="row.editName" size="small" placeholder="属性名" />
                 <span v-else>{{ row.name }}</span>
             </template>
          </el-table-column>
          <el-table-column prop="value" label="值">
             <template #default="{ row }">
                 <el-input v-if="row.isEditing" v-model="row.editValue" size="small" placeholder="属性值" />
                 <span v-else>{{ row.value }}</span>
             </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ row, $index }">
              <div v-if="row.isEditing">
                 <el-button type="success" :icon="Check" size="small" circle @click="saveAttribute(row, $index)" />
                 <el-button type="info" :icon="Close" size="small" circle @click="cancelEditAttribute(row, $index)" />
              </div>
              <div v-else>
                <el-button type="primary" :icon="Edit" size="small" circle @click="editAttribute(row)" />
                <el-popconfirm title="确定删除此属性吗?" @confirm="deleteAttr(row.name)">
                  <template #reference>
                    <el-button type="danger" :icon="Delete" size="small" circle />
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- Add Attribute Form -->
        <el-form 
            ref="addAttributeFormRef" 
            :model="newAttribute" 
            :rules="addAttributeRules"
            label-position="top"
            size="small"
            class="add-attribute-form"
            @submit.prevent="submitAddAttribute"
        >
            <el-row :gutter="10">
                <el-col :span="10">
                    <el-form-item label="新属性名" prop="name">
                        <el-input v-model="newAttribute.name" placeholder="属性名"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="10">
                    <el-form-item label="新属性值" prop="value">
                        <el-input v-model="newAttribute.value" placeholder="属性值"></el-input>
                    </el-form-item>
                </el-col>
                 <el-col :span="4" style="display: flex; align-items: flex-end; padding-bottom: 7px;"> 
                     <el-button type="success" native-type="submit" :icon="Plus" circle title="添加属性" />
                 </el-col>
            </el-row>
        </el-form>
      </div>

      <!-- Text Content -->
      <el-divider>文本内容</el-divider>
      <div class="text-content-section">
        <el-input
          v-model="editableTextContent"
          type="textarea"
          :rows="4"
          placeholder="节点无文本内容"
          :disabled="!nodeData?.data"
        />
         <el-button 
             type="primary" 
             size="small" 
             @click="saveTextContent"
             :disabled="!isTextContentDirty"
             style="margin-top: 10px;"
         >
             保存文本更改
         </el-button>
      </div>
    </div>
    <el-empty v-else description="未选择节点"></el-empty>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, computed, watch, reactive } from 'vue';
// Import the correct store
import { useEditorStore } from '@/stores/editorStore.ts';
import { ElDrawer, ElDescriptions, ElDescriptionsItem, ElDivider, ElTable, ElTableColumn, ElInput, ElButton, ElPopconfirm, ElForm, ElFormItem, ElRow, ElCol, ElEmpty, ElMessage } from 'element-plus';
import { Edit, Delete, Check, Close, Plus } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';
import type { FlowNode } from '@/models/jdf'; // Assuming FlowNode is defined here

// Use the editor store instance
const editorStore = useEditorStore();

// Get node data from the store getter
const nodeData = computed(() => editorStore.drawerNodeData);

const drawerTitle = computed(() => {
    return nodeData.value ? `节点详情: ${nodeData.value.data.nodeName}` : '节点详情';
});

// --- Attribute Editing State & Logic ---
const addAttributeFormRef = ref<FormInstance>();
const newAttribute = reactive({ name: '', value: '' });
const addAttributeRules = reactive<FormRules>({
    name: [
        { required: true, message: '属性名不能为空', trigger: 'blur' },
        // Basic XML name validation (start with letter or _, then letter, digit, ., -, _)
        { pattern: /^[a-zA-Z_][a-zA-Z0-9_.-]*$/, message: '无效的XML属性名', trigger: 'blur' }
    ],
    // Value can be anything, no specific rules needed here unless required
    // value: [{ required: true, message: '属性值不能为空', trigger: 'blur' }]
});

// Temporary storage for editing attributes to allow cancellation
let originalAttributeValues: { [key: string]: { name: string; value: string } } = {}; 

const editAttribute = (row: any) => {
    // Store original values before entering edit mode
    originalAttributeValues[row.name] = { name: row.name, value: row.value };
    row.editName = row.name; // Initialize edit fields
    row.editValue = row.value;
    row.isEditing = true;
};

const cancelEditAttribute = (row: any, index: number) => {
    // Restore original values if they exist
    if (originalAttributeValues[row.name]) {
       // No need to directly modify row.name/value here if we just exit edit mode
    }
    row.isEditing = false;
    // Clean up temporary storage
    delete originalAttributeValues[row.name];
};

const saveAttribute = async (row: any, index: number) => {
    if (!nodeData.value) return;
    
    const originalName = originalAttributeValues[row.name]?.name ?? row.name; // Get original name for store update
    const newName = row.editName.trim();
    const newValue = row.editValue; // No trim needed for value generally

    // Basic validation
    if (!newName) {
        ElMessage.error('属性名不能为空');
        return;
    }
     if (!/^[a-zA-Z_][a-zA-Z0-9_.-]*$/.test(newName)) {
         ElMessage.error('无效的XML属性名');
         return;
     }
     // Check for name collision (only if name changed)
     if (newName !== originalName && nodeData.value.data.attributes.some((attr: any, i: number) => i !== index && attr.name === newName)) {
         ElMessage.error(`属性名 "${newName}" 已存在`);
         return;
     }

    try {
        // Call store action to update attribute
        await editorStore.updateNodeAttribute({
            nodeId: nodeData.value.id,
            oldName: originalName,
            newName: newName,
            newValue: newValue,
        });
        row.isEditing = false; // Exit editing mode on success
        delete originalAttributeValues[row.name]; // Clean up temp storage
        ElMessage.success('属性已更新');
    } catch (error: any) { // Catch potential errors from store action
        console.error("Failed to save attribute:", error);
        ElMessage.error(`保存属性失败: ${error.message || '未知错误'}`);
        // Optionally restore original values in UI on failure?
        // row.editName = originalName;
        // row.editValue = originalAttributeValues[row.name]?.value ?? row.value;
    }
};

const deleteAttr = async (attributeName: string) => {
    if (!nodeData.value) return;
    try {
        // Call store action to delete attribute
        await editorStore.deleteAttribute({
            nodeId: nodeData.value.id,
            attributeName: attributeName,
        });
        ElMessage.success(`属性 "${attributeName}" 已删除`);
    } catch (error: any) { // Catch potential errors from store action
        console.error("Failed to delete attribute:", error);
        ElMessage.error(`删除属性失败: ${error.message || '未知错误'}`);
    }
};

const submitAddAttribute = async () => {
    if (!addAttributeFormRef.value || !nodeData.value) return;
    await addAttributeFormRef.value.validate(async (valid) => {
        if (valid) {
             // Check for name collision before adding
             if (nodeData.value?.data.attributes.some((attr: any) => attr.name === newAttribute.name.trim())) {
                 ElMessage.error(`属性名 "${newAttribute.name.trim()}" 已存在`);
                 return;
             }
            try {
                // Call store action to add attribute
                await editorStore.addAttribute({
                    nodeId: nodeData.value!.id,
                    name: newAttribute.name.trim(),
                    value: newAttribute.value,
                });
                ElMessage.success('属性已添加');
                // Reset form
                addAttributeFormRef.value?.resetFields();
                newAttribute.name = '';
                newAttribute.value = '';
            } catch (error: any) { // Catch potential errors from store action
                console.error("Failed to add attribute:", error);
                ElMessage.error(`添加属性失败: ${error.message || '未知错误'}`);
            }
        }
    });
};

// --- Text Content Editing --- 
const editableTextContent = ref('');
const isTextContentDirty = ref(false);

watch(nodeData, (newNode) => {
    if (newNode) {
        editableTextContent.value = newNode.data.textContent || '';
    } else {
        editableTextContent.value = '';
    }
    isTextContentDirty.value = false; // Reset dirty flag when node changes
}, { immediate: true });

watch(editableTextContent, (newText) => {
    if (nodeData.value && newText !== (nodeData.value.data.textContent || '')) {
        isTextContentDirty.value = true;
    } else {
        isTextContentDirty.value = false;
    }
});

const saveTextContent = async () => {
    if (!nodeData.value || !isTextContentDirty.value) return;

    // TODO: Implement text content saving logic in editorStore if needed.
    // This might involve generating new XML or finding a way to update text nodes.
    // For now, we'll just show a message and potentially reset the dirty flag.

    // Example: Call a hypothetical store action
    // try {
    //    await editorStore.updateNodeTextContent({ 
    //        nodeId: nodeData.value.id, 
    //        newText: editableTextContent.value 
    //    });
    //    ElMessage.success('文本内容已保存');
    //    isTextContentDirty.value = false;
    // } catch (error: any) {
    //    ElMessage.error(`保存文本内容失败: ${error.message}`);
    // }
    
    ElMessage.warning('保存文本内容的功能尚未完全实现。'); 
    // isTextContentDirty.value = false; // Reset dirty flag for now
};

// --- Drawer Closing Logic --- 
const handleClose = () => {
    // Call store action to clear the selected node ID for the drawer
    editorStore.selectNodeForDrawer(null);
};

</script>

<style lang="scss" scoped>
.node-details-drawer :deep(.el-drawer__header) {
    margin-bottom: 15px; /* Add some space below the header */
}

.drawer-content {
    padding: 0 10px; /* Add some padding */
}

.node-info-section,
.attributes-section,
.text-content-section {
    margin-bottom: 20px;
}

.add-attribute-form {
    margin-top: 15px;
}

/* Make table cells less padded */
.attributes-section :deep(.el-table .el-table__cell) {
    padding: 4px 0;
}
</style>